//index.js
//获取应用实例
const app = getApp()
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
var videopage = 1;
Page({
 
  data:{
    swiperCurrent:0,
    curswiperIndex:0,
    isPlay:true,
    videoList: [],//视频列表
    videoInfo:[],
    page:1,
    pages:2,
    file_id:888,
		search:'',
    curvideo: {},//当前视频
    cururl:'',//当前视频路径
    videoindex: 0,
    videoH: 600,//高度
    videoBtnStatus: 'none',//视频按钮状态
		likes:0,
    show:false,
    nolaud:true,
    commentList:[],
    isFocus:false,
    isReply:false,
    isReplys:false,
    reply_holder:'说点什么',
    commentStr:'',//评论内容
    type:1,//回复层级 默认为1 最大为2
    v_r_id:0//回复上级id
  },
  // 设置分享到朋友圈的标题
  onShareTimeline:function(){
    const that = this
    return {
      title:'智克艺术-'+that.data.curvideo.school_name +'-'+that.data.curvideo.filetitle,
      query:'file_id='+that.data.curvideo.file_id,
      imageUrl:that.data.curvideo.fileimg
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true,
      menus:['shareAppMessage', 'shareTimeline']
    })
    let file_id = options.file_id
    if(file_id){
      this.setData({
        file_id
      })
      this.getVideoInfo(this.data.file_id)
      return
    }
    var obj = wx.getLaunchOptionsSync()
    if(obj.scene==1154||obj.scene==1155){
      this.getVideoInfo()
    }
    wx.getUserInfo({
      success: res => {
        var userInfo = res.userInfo
        this.setData({
          userInfo
        })
      }
    })
    var that = this;
    videopage = 0;
    wx.getSystemInfo({//适配
      success: function (res) {
        that.setData({
          videoH:res.windowHeight
        })
      }
    })
    wx.showLoading({
      title: '加载中...',
    });
    that.getVideoList(1);
    
    setTimeout(function(){
      let curvideo = that.data.videoList[0]
      that.setData({
        curvideo
      })
      if(curvideo.video_like==0){
        that.setData({
          nolaud:true
        })
      }else if(curvideo.video_like==1){
        that.setData({
          nolaud:false
        })
      }
      that.getCommentList(1)
    },1000)
    let token = wx.getStorageSync('token')
    let uuid = '游客'+token.slice(5,10)
    that.setData({uuid})
  },
  //生命周期函数--监听页面初次渲染完成
  onReady:function(){
  },
  onShow:function(){
  },
  updateLaud(file_id){
    const that = this
    let token = wx.getStorageSync('token')
    wx.request({
      url: app.globalData.host+'Video/index_free_one',
      method:'POST',
      data:{file_id,token},
      success(res){
        let curvideo = that.data.curvideo
        curvideo = res.data.data
        that.setData({
          curvideo
        })
      }
    })
  },
  getVideoInfo(file_id,page){
    const that = this
    let params = {
      page,
      file_id,
      token:wx.getStorageSync('token')
    }
    wx.request({
      url: app.globalData.host+'Video/video_list',
      method:'GET',
      data:params,
      success(res){
        let videoInfo = that.data.videoInfo
        let videoInfo1 = res.data.data
        if (page == 1) {
            videoInfo = res.data.data
        } else {
          videoInfo = [...videoInfo, ...videoInfo1]
        }
        let curvideo = {}
        that.setData({
          videoInfo,
          curvideo:videoInfo
        })
      },
      fail(err){
        wx.showToast({
          title: res.data.msg,
          icon:'none'
        })
      }
    })
  },
  // 返回上一级
  back(){
    wx.reLaunch({
      url: '/pages/video/video',
    })
  },
	// 点赞
	laudtap(e){
    // console.log(e)
	  const that = this
	  let file_id = e.target.dataset.fileid
    let v_like = that.data.curvideo.video_like
    let curvideo = that.data.curvideo
    var token = wx.getStorageSync('token')
	  if(v_like==0){
      // 点赞
	    let status = 1
	    wx.request({
	      url: app.globalData.host+'VideoToken/up',
	      method:'POST',
	      data:{status,file_id,token},
	      success(res){
	        if(res.data.code==5001){
	          wx.showToast({
	            title: 'token已失效,请您重新登录',
	            icon:'none'
	          })
	          wx.switchTab({
	            url: '/pages/personal/personal',
	          })
	          return
	        }else if(res.data.code==2001){
	          wx.showToast({
	              title: res.data.msg,
	              icon:'none'
	          })
	          return
	        }
	        wx.showToast({
	          title: res.data.msg,
	          icon:'none'
          })
          that.updateLaud(file_id)
          let likes = res.data.data
	        that.setData({
            nolaud:false,
            likes
	        })
	      },
	      fail(err){
          wx.showToast({
	          title: res.data.msg,
	          icon:'none'
	        })
	      }
	    })
	  }else if(v_like==1){
      // 取消点赞
	    let status = 0
	    wx.request({
	      url: app.globalData.host+'VideoToken/up',
	      method:'POST',
	      data:{status,file_id,token},
	      success(res){
	        if(res.data.code==5001){
	          wx.showToast({
	            title: 'token已失效,请您重新登录',
	            icon:'none'
	          })
	          wx.switchTab({
	            url: '/pages/personal/personal',
	          })
	          return
	        }
	        wx.showToast({
	          title: res.data.msg,
	          icon:'none'
          })
          that.updateLaud(file_id)
          let likes = res.data.data
	        that.setData({
            nolaud:true,
            likes
	        })
	      },
	      fail(err){
	        console.log(err)
	      }
	    })
	  }else{
      wx.showToast({
        title: '请登录后再点赞',
        icon:'none',
        duration:2000
      })
    }
  },
  // 跳转到评论页
  goCommentDetail(e){
    let id = e.currentTarget.dataset.fileid
    wx.navigateTo({
      url: '/pages/video_comment/video_comment?file_id='+id,
    })
  },
   //获取视频列表
   getVideoList: function (){
		let page = this.data.page
    let search  = this.data.search 
    let token = wx.getStorageSync('token')
    let params={
    	page,
      search,
      token
    }
    const that = this
    wx.request({
    	url: app.globalData.host+'Video/index_free',
    	method:'GET',
    	data:params,
    	success(res){
    		let videoList = that.data.videoList
    		let videoList1 = res.data.data
    		if (page == 1) {
    			videoList = res.data.data;
    		} else {
    			videoList = [...videoList, ...videoList1]
    		}
				let likes = videoList[that.data.videoindex].likes
				page++
    		that.setData({
    			videoList,
					page,
					likes
    		})
    	},
    	fail(err){
    		wx.showToast({
    			title: res.data.msg,
    		})
    	}
    })
    wx.hideLoading();
  },
  //监听视频播放进度
  // videoProgress: function (e) {
  //   var that = this;
  //   var duration = e.detail.duration;
  //   var currentTime = e.detail.currentTime;
  //   var progress = currentTime / duration * 100;
  //   that.setData({
  //     vProgress: progress
  //   })
  // },
  startPlay:function(){
    var that = this
    if(that.data.isPlay==false){
      that.setData({
        isPlay:true
      })
    }
  },
  //视频播放时
  videoPlay:function(){
  },
  touchstart(){
   
  },
  //切换视频时
  changeVideo:function (e){
    console.log(e)
    var that  = this;
    var show = that.data.show
    if(e.detail.source == 'touch'){
      this.setData({
        swiperCurrent: e.detail.current //获取当前轮播图片的下标
      })
    }
    var curswiperIndex = e.detail.current
    //判断是否结束
    var count = that.data.videoList.length
    if(count==(curswiperIndex+1)){
			console.log('没有了')
      that.getVideoList(that.data.page,'')
    }
    var lastIndex = that.data.curswiperIndex
        //判断是上滑还是下滑
        that.setData({
        curswiperIndex:curswiperIndex
      })
      var videoindex = that.data.videoindex;
      if(curswiperIndex>lastIndex){
        //上滑
        videopage++
        videoindex = videopage
        var curvideo = that.data.videoList[videoindex]
        if(curvideo.video_like==0){
          this.setData({
            nolaud:true
          })
        }else if(curvideo.video_like==1){
          this.setData({
            nolaud:false
          })
        }
        that.setData({
          videoindex:videoindex,
          curvideo:curvideo,
          videoBtnStatus:'none',
          likes:curvideo.likes,
          show:false
        })
        that.getCommentList(1)
   }else{
     //下滑
      videopage--
      videoindex = videopage
      var curvideo = that.data.videoList[videoindex]
      if(curvideo.video_like==0){
        this.setData({
          nolaud:true
        })
      }else if(curvideo.video_like==1){
        this.setData({
          nolaud:false
        })
      }
      that.setData({
          videoindex:videoindex,
          curvideo:curvideo,
          videoBtnStatus:'none',
          likes:curvideo.likes,
          show:false
      })
      that.getCommentList()
    }
  },
  //点击视频暂停
  pauseVideo:function(){
    var that = this; 
    if(that.data.videoBtnStatus){
      wx.createVideoContext("video"+that.data.videoindex).pause()
      that.setData({
        videoBtnStatus:'block'
      })
    }
  },
  //点击播放按钮
  playVideo:function(){
    var that = this; 
    wx.createVideoContext("video"+that.data.videoindex).play()
    that.setData({
      videoBtnStatus:'none'
    })
  },
	// 拉起评论列表
	pullup(){
    this.setData({
        show:true
    })
    if(this.data.commentList==''){
      this.setData({
        noComments:true
      })
    }
	},
	// 关闭评论列表
	onClose(){
    this.setData({
        show:false
    })
  },
  // 评论模块
  // 输入框确认事件
  addFirstCom(isReply,isReplys,type,v_r_id){
    // 如果是回复状态
    isReply = this.data.isReply
    isReplys = this.data.isReplys
    if(isReply){
      let type = this.data.reply1_type
      let v_r_id = this.data.reply1_v_r_id
      this.addComment(type,v_r_id)
    }else if(isReplys){
      let type = this.data.reply2_type
      let v_r_id = this.data.reply2_v_r_id
      this.addComment(type,v_r_id)
    }else{
      let type = 1
      let v_r_id = 1
      this.addComment(type,v_r_id)
    }
  },
  // 添加评论
  addComment(type,v_r_id){
    if(this.data.commentStr==''){
      wx.showToast({
        title: '评论内容不能为空',
        icon:'none'
      })
      return
    }
    const that = this
    let file_id = that.data.curvideo.file_id
    let content=that.data.commentStr
    let token = wx.getStorageSync('token')
    let username=that.data.userInfo.nickName
    let user_img=that.data.userInfo.avatarUrl
    wx.request({
      url: app.globalData.host+'Video/add_comment',
      method:'POST',
      data:{
        file_id,
        type,
        v_r_id,
        content,
        username,
        user_img,
        token,
      },
      success(res){
        that.setData({
          isFocus:false,
          isReply:false,
          isReplys:false,
          commentStr:'',
          reply_holder:'说点什么'
        })
        if(res.data.code==2000){
          wx.showToast({
            title: '添加评论成功',
            icon:'none'
          })
        }else{
          wx.showToast({
            title: res.data.msg,
            icon:'none'
          })
        }
        that.getCommentList()
      }
    })
  },
  // 回复1级评论
  reply1(e){
    let u_name = e.currentTarget.dataset.name
    let type=2
    let v_r_id = e.currentTarget.dataset.id
    this.setData({
      isFocus:true,
      isReply:true,
      reply1_type:type,
      reply1_v_r_id:v_r_id,
      reply_holder:'回复@'+u_name
    })
  },
  // 回复2级评论
  reply2(e){
    let type=2
    let v_r_id = e.currentTarget.dataset.id
    let u_name = e.currentTarget.dataset.name
    this.setData({
      isFocus:true,
      isReply:false,
      isReplys:true,
      reply2_type:type,
      reply2_v_r_id:v_r_id,
      reply_holder:'回复@'+u_name
    })
  },
  // 输入/提交评论
  setStr(e){
    let val = e.detail.value
    let commentStr = this.data.commentStr
    this.setData({
      commentStr:val.replace(/\s+/g,'')
    })
  },
  foucsup(){
    this.setData({
      isFocus:true,
      isReply:false,
    })
  },
  // 获取评论
  getCommentList(pages){
    const that = this
    pages = that.data.pages
    let file_id = that.data.curvideo.file_id
    wx.request({
      url: app.globalData.host+'Video/comment_list',
      method:'POST',
      data:{
        file_id,
        pages
      },
      success(res){
        let commentList = that.data.commentList
        commentList = res.data.data
        
        for(var index in commentList){
          var commentTime = new Date(commentList[index].create_time*1000).dateFormat('Y年m月d日')
          commentList[index].create_time = commentTime
        }
        pages++
        that.setData({
          commentList,
          commentStr:'',
          pages
          // length
        })
      },
      fail(err){
        console.log(err)
      }
    })
  },
  // 统计评论总条数
  getCommentSum(){
    let list = this.data.commentList
    if(list.length!==0){
      let lastID = list[list.length-1].id
      // if(list[list.length-1].reply_arr!==''){
      //   let lastID_child1 = list[list.length-1].reply_arr[list[list.length-1].reply_arr.length-1].id
      // }else if(list[list.length-1].reply_arr[list[list.length-1].reply_arr!==''){

      // }
      this.setData({
        length:lastID
      })
    }else{
      this.setData({
        length:0
      })
    }
  },
  onReachBottom:function(){
    this.getCommentList(this.data.pages)
  },
  onShareAppMessage: function(options) {
    var that = this;
　　// 设置菜单中的转发按钮触发转发事件时的转发内容
　　var shareObj = {
　　　　title: '智克艺术-'+that.data.curvideo.school_name +'-'+that.data.curvideo.filetitle,        // 默认是小程序的名称(可以写slogan等)
　　　　path: '/pages/scroll_video/scroll_video?file_id='+that.data.curvideo.file_id,        // 默认是当前页面，必须是以‘/’开头的完整路径  
　　　　imageUrl: that.data.curvideo.fileimg,     //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
　　　　success: function(res){
　　　　　　// 转发成功之后的回调
　　　　　　if(res.errMsg == 'shareAppMessage:ok'){
              wx.showToast({
                title: '分享成功!',
              })
           }
　　　　},
　　　　fail: function(){
　　　　　　// 转发失败之后的回调
　　　　　　if(res.errMsg == 'shareAppMessage:fail cancel'){
　　　　　　　　// 用户取消转发
　　　　　　}else if(res.errMsg == 'shareAppMessage:fail'){
　　　　　　　　// 转发失败，其中 detail message 为详细失败信息
　　　　　　}
　　　　}
　　}
　　// 来自页面内的按钮的转发
// 　　if( options.from == 'button' ){
// 　　　　var eData = options.target.dataset
// 　　　　console.log( eData.name )    // shareBtn
// 　　　　// 此处可以修改 shareObj 中的内容
// 　　　　shareObj.path = '/pages/btnname/btnname?btn_name='+eData.name
// 　　}
　　// 返回shareObj
　　return shareObj;
  }
})
